package com.demo.my.Controller;


import com.demo.my.Entity.Department;
import com.demo.my.Entity.Employee;
import com.demo.my.Service.DepartmentService;
import com.demo.my.Service.EmployeeService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

//高和召
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private EmployeeService employeeService=new EmployeeService();
    private DepartmentService departmentService=new DepartmentService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String employeeNumber = req.getParameter("employeeNumber");
        String password = req.getParameter("password");
        Employee employee=employeeService.getEmployee(employeeNumber,password);
        System.out.println(employee);
        if (employee!=null){
            HttpSession session = req.getSession();
            try {
                boolean isManager=false;
                List<Department> depList = departmentService.getDepList();
                for (Department department : depList) {
                    if(department.getManager()!=null&&department.getManager().equals(employeeNumber)){
                        isManager=true;
                        break;
                    }
                }
                session.setAttribute("isManager",isManager);
            } catch (Exception e) {
                e.printStackTrace();
            }
            session.setAttribute("user_info",employee);
            req.getRequestDispatcher("/jsp/admin/home.jsp").forward(req,resp);
        }else {
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("<script type=\"text/javascript\">\n" +
                    "\talert(\"登陆失败\")\n" +
                    "\tsetTimeout(function () {\n" +
                    "\t\twindow.location.href = \"/jsp/login.jsp\";\n" +
                    "    },100)\n" +
                    "</script>");
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
